package com.sobiesz.headsetcontrol;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;



import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Application;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.android.internal.telephony.*;

public class MainActivity extends FragmentActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;
    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        
   	 Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
   	 headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
   	 headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged  1 = Headset with microphone 2 = Headset without microphone
   	 headSetUnPluggedintent.putExtra("name", "Headset");
   	 // TODO: Should we require a permission?
   	 this.sendOrderedBroadcast(headSetUnPluggedintent, null);       	        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment implements  BluetoothProfile.ServiceListener {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
    	Context mContext;
    	private static final String TAG = "Bluetooth Headset"; 
    	
        public static final String ARG_SECTION_NUMBER = "section_number";
        BluetoothHeadset  mBluetoothHeadset = null;
         TextView dummyTextView;
         protected BluetoothDevice mConnectedHeadset;
         
         public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.HEADSET) {
                mBluetoothHeadset = (BluetoothHeadset) proxy;
                List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
                if (devices.size() > 0)
                {
                    // Only one head set can be connected at a time, 
                    // so the connected head set is at index 0.
                    mConnectedHeadset = devices.get(0);

                    String log = "";

                    // The audio should not yet be connected at this stage.
                    // But just to make sure we check.
                    if (( mBluetoothHeadset).isAudioConnected(mConnectedHeadset))
                    {
                        log = "Profile listener audio already connected"; //$NON-NLS-1$     
                    }
                    else
                    {

                    }

                    dummyTextView.setText("Device name = " + mConnectedHeadset.getName() //$NON-NLS-1$
                                            + "\n\n" + log); //$NON-NLS-1$
                    Log.d(TAG, log); 
                }

                // During the active life time of the app, a user may turn on and off the head set.
                // So register for broadcast of connection states.
                mContext.registerReceiver(mHeadsetBroadcastReceiver, 
                                new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED));                
            }
        }
        public void onServiceDisconnected(int profile) {
        	Toast.makeText(mContext, "disconnect", 5).show();
            if (profile == BluetoothProfile.HEADSET) {
                mBluetoothHeadset = null;
            }
       }
        
        protected BroadcastReceiver mHeadsetBroadcastReceiver = new BroadcastReceiver()
        {

            @Override
            public void onReceive(Context context, Intent intent)
            {
                String action = intent.getAction();
                int state;
                int previousState = intent.getIntExtra(BluetoothHeadset.EXTRA_PREVIOUS_STATE, BluetoothHeadset.STATE_DISCONNECTED);
                String log = ""; //$NON-NLS-1$
                if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED))
                {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_DISCONNECTED);
                    if (state == BluetoothHeadset.STATE_CONNECTED)
                    {
                        mConnectedHeadset = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                        dummyTextView.append("\n\nDevice name = " + mConnectedHeadset.getName()); //$NON-NLS-1$

                        // Audio should not be connected yet but just to make sure.
                        if (mBluetoothHeadset.isAudioConnected(mConnectedHeadset))
                        {
                            log = "Headset connected audio already connected"; //$NON-NLS-1$
                        }
                        else
                        {
 
                        }
                    }
                    else if (state == BluetoothHeadset.STATE_DISCONNECTED)
                    {
                        // Calling stopVoiceRecognition always returns false here
                        // as it should since the headset is no longer connected.
                        mConnectedHeadset = null;
                    }
                }
                else // audio
                {
                    state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
                    if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED)
                    {
                        log = "Head set audio connected, cancel countdown timer";  //$NON-NLS-1$
                      
                    }
                    else if (state == BluetoothHeadset.STATE_AUDIO_DISCONNECTED)
                    {
                        // The headset audio is disconnected, but calling
                        // stopVoiceRecognition always returns true here.
                       boolean returnValue = mBluetoothHeadset.stopVoiceRecognition(mConnectedHeadset);
                        log = "Audio disconnected stopVoiceRecognition return " + returnValue; //$NON-NLS-1$
                    }
                }   

                log += "\nAction = " + action + "\nState = " + state //$NON-NLS-1$ //$NON-NLS-2$
                        + " previous state = " + previousState; //$NON-NLS-1$
                dummyTextView.append("\n\n" + log); //$NON-NLS-1$
                Log.d(TAG, log);
            }
        };
        
        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
            dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
            dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
            
           // ListView lv = (ListView) rootView.findViewById(R.id.listView1);
         //   blueadp ba = new blueadp(lv.getContext());
        //    lv.setAdapter(ba);
            
            mContext = rootView.getContext();
            Toast.makeText(mContext, "created", 5).show();
            BluetoothAdapter mBluetoothAdapter = null;
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if(mBluetoothAdapter!=null)
            	mBluetoothAdapter.getProfileProxy(rootView.getContext(), this, BluetoothProfile.HEADSET);

            mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
            mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
            return rootView;
        
    
 
        }      
        TelephonyManager mTelephonyManager ;
  
        
        PhoneStateListener mPhoneListener = new PhoneStateListener() {
        	  @SuppressWarnings({ "rawtypes", "unchecked" })
			public void onCallStateChanged(int state, String incomingNumber) {
        	   try {
        	    switch (state) {
        	    case TelephonyManager.CALL_STATE_RINGING:
        	    	dummyTextView.append("RINGING\n");
        	    	 Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);          
        	    	 buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
        	    	 mContext.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");

        	    	 // froyo and beyond trigger on buttonUp instead of buttonDown
        	    	 Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);            
        	    	 buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
        	    	 mContext.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");

        	    	 Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
        	    	 headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        	    	 headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged  1 = Headset with microphone 2 = Headset without microphone
        	    	 headSetUnPluggedintent.putExtra("name", "Headset");
        	    	 // TODO: Should we require a permission?
        	    	 mContext.sendOrderedBroadcast(headSetUnPluggedintent, null);       	    	
        	    /*	 
        	    	 headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG );
        	    	 headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        	    	 headSetUnPluggedintent.putExtra("state", 0); // 0 = unplugged  1 = Headset with microphone 2 = Headset without microphone
        	    	 headSetUnPluggedintent.putExtra("name", "Headset");
        	    	 // TODO: Should we require a permission?
        	    	 mContext.sendOrderedBroadcast(headSetUnPluggedintent, null); */        	    	 
        	     break;
        	    case TelephonyManager.CALL_STATE_OFFHOOK:
        	    	dummyTextView.append("OFF HOOK\n");
        	     break;
        	    case TelephonyManager.CALL_STATE_IDLE:
        	    	dummyTextView.append("IDLE\n");
        	     break;
        	    }
        	   } catch (Exception e) {
        	    Log.i("Exception", "PhoneStateListener() e = " + e);
        	   }
        	  }
        	 };        
    
    public class blueadp extends BaseAdapter {
    	public class elem
    	{
    		public String name;
    		public String addrs;
    	}
    	public List<elem> list = new ArrayList<elem>();
    	Context mContext;
    	public blueadp(Context context)
    	{
    		super();
    		mContext = context;
            BluetoothAdapter mBluetoothAdapter = null;
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if(mBluetoothAdapter != null)
            {
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                if (pairedDevices.size() != 0)
                {
                    // the device has paired devices
                    for (BluetoothDevice device : pairedDevices)
                    {
                    	elem e = new elem();
                    	e.name = device.getName();
                    	e.addrs = device.getBluetoothClass().toString();
                    	
                        Log.i("info", "device name: " + device.getName());
                        Log.i("info", "device address: " + device.getAddress());
                    }
                }
                else
                {
                    // no paired devices
                    Log.i("info", "no paired devices");
                }
                
         
            }    		
    	}
    	@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0).hashCode();
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if(arg1==null)
			{
				View v = View.inflate(mContext, R.layout.list_elem , null);
				((TextView)v.findViewById(R.id.textView1)).setText(list.get(arg0).name);
				((TextView)v.findViewById(R.id.textView2)).setText(list.get(arg0).addrs);
				return v;
			}
			else
				
			return arg1;
		}
    	
    }

    }
}
